package cn.ml.web1662.commons;

import java.sql.*;
import java.util.List;
import java.util.Properties;

/**
 * 数据库工具类
 */
public abstract class DBHelp {
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();//本地线程作用域
    private DBHelp(){

    }

    /**
     * 打开数据库连接
     * 连接保存到了本地线程作用域中
     */
    public static void open() {
        Properties pros = new Properties();
        try {
            pros.load(DBHelp.class.getClassLoader().getResourceAsStream("datasource.properties"));
            Class.forName(pros.getProperty("driver"));
            threadLocal.set(DriverManager.getConnection(pros.getProperty("url"),pros.getProperty("username"),pros.getProperty("password")));
        } catch (Exception e) {
            throw new RuntimeException("自定义异常",e);
        }
    }

    public static void execute(String sql, List params) {
        try (PreparedStatement st = threadLocal.get().prepareStatement(sql)) {
            if(params!=null){
                for(int i=0;i<params.size();i++){
                    st.setObject(i+1,params.get(i));
                }
            }
            st.execute();
        } catch (SQLException e) {
            throw new RuntimeException("自定义一床",e);
        }
    }

    public static interface CallBack{
        void work(ResultSet rs) throws SQLException;
    }
    public static void executeQuery(String sql, List params,CallBack cb){

        try (PreparedStatement st = threadLocal.get().prepareStatement(sql)) {
            if(params!=null){
                for(int i=0;i<params.size();i++){
                    st.setObject(i+1,params.get(i));
                }
            }
            try(ResultSet rs = st.executeQuery()){
                cb.work(rs);
            }
        } catch (SQLException e) {
            throw new RuntimeException("自定义异常",e);
        }

    }

    public static void close() {
        Connection connection = threadLocal.get();
        try {
            if(connection!=null&&!connection.isClosed()){
                connection.close();
            }
        } catch (Exception e) {
            throw new RuntimeException("自定义异常",e);
        }
    }
}
